﻿using AutoMapper;
using MediatR;
using Traceability.Domain;
using Traceability.ErrorCode;
using Traceability.Infrastructure;

namespace Traceability.App.Applications.Company
{
    public class CompanyAddCommandHandler : IRequestHandler<CompanyAddCommand, APIResult<int>>
    {
        private readonly IBaseRepository<T_Company> companyRepository;
        private readonly IMapper mapper;

        public CompanyAddCommandHandler(IBaseRepository<T_Company> companyRepository, IMapper mapper)
        {
            this.companyRepository = companyRepository;
            this.mapper = mapper;
        }

        public async Task<APIResult<int>> Handle(CompanyAddCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            result.Code = APIEnum.ok;
            result.Message = "设置成功";
            var model = mapper.Map<T_Company>(request);
            var records = companyRepository.GetAll().FirstOrDefault(x => x.ID == request.ID);
            if (records == null)
            {
                model.ID = 0;
                result.Data = await companyRepository.Add(model);
                return await Task.FromResult(result);
            }
            else 
            {
                var models = mapper.Map(request, records);
                result.Data = await companyRepository.Update(models);
                return await Task.FromResult(result);
            }
           
        }
    }
}
